package com.drore.cloud.controller.sys;

import com.drore.cloud.domain.sys.RestMessage;
import com.drore.cloud.service.VerifyService;
import io.swagger.annotations.Api;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;

/***
 * 浙江卓锐科技股份有限公司 版权所有@Copyright 2016
 * 说明
 * 项目名称
 * @since:cloud-ims 1.0
 * @author <a href="mailto:baoec@drore.com">baoec@drore.com </a> 
 * 2017/11/16 15:12
 */
@Api("滑动验证码")
@RestController
@RequestMapping("/cms/slide_verify")
public class SlideVerifyCtl {
    @Resource
    private VerifyService verifyService;

    @GetMapping("test")
    public String init(){
        return "/drawDemo";
    }


    @RequestMapping("i")
    @ResponseBody
    public synchronized   RestMessage generateCode(HttpSession session) throws Exception{
        RestMessage rm = new RestMessage();
//        Challenge challenge = (Challenge)session.getAttribute("CHALLENGE");
//        if(challenge==null){
//            throw new MacroApiException("网络不给力");
//        }
//        if(challenge.getNum()>2){
//            throw new MacroApiException("出错次数过多，休息一下");
//        }else {
//            challenge.setNum(challenge.getNum()+1);
//        }
        rm.setData(verifyService.generate(session));
        return rm;
    }
    @PostMapping("verify")
    @ResponseBody
    public RestMessage verify(@RequestParam("code")String code
            ,@RequestParam("value")int value,HttpSession session) throws Exception{
        RestMessage rm = new RestMessage();
        boolean result = session.getAttribute(code)!=null;
        System.out.println("code:"+code);
        System.out.println("value:"+value);
        if(result){
            int _x= (int) session.getAttribute(code);
            session.removeAttribute(code);
            int offset = _x - value;
            if(offset <= 2 && offset >= -2){
                rm.setMessage("验证成功，可登陆");
                return rm;
            }
        }
        session.removeAttribute(code);
        rm.setSuccess(false);
        rm.setMessage("滑动验证失败");
        return rm;
    }

    @RequestMapping("load")
    public void load(@RequestParam("code")String code
            ,HttpServletResponse response) throws FileNotFoundException, IOException {
        code = URLDecoder.decode(code, "utf-8");
        InputStream in = IOUtils.toBufferedInputStream(new FileInputStream(new File(code)));
        ServletOutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024 * 8];
        int length = 0;
        while((length = in.read(buf)) != -1){
            out.write(buf, 0, length);
        }
        out.flush();
        out.close();
    }
}
